a tool for shared writing and social publishing
1import { z } from "zod";
2import { makeRoute } from "../lib";
3import type { Env } from "./route";
4import { getPublicationURL } from "app/lish/createPub/getPublicationURL";
5import { deduplicateByUri } from "src/utils/deduplicateRecords";
6
7export type SearchPublicationNamesReturnType = Awaited<
8 ReturnType<(typeof search_publication_names)["handler"]>
9>;
10
11export const search_publication_names = makeRoute({
12 route: "search_publication_names",
13 input: z.object({
14 query: z.string(),
15 limit: z.number().optional().default(10),
16 }),
17 handler: async ({ query, limit }, { supabase }: Pick<Env, "supabase">) => {
18 // Search publications by name in record (case-insensitive partial match)
19 const { data: rawPublications, error } = await supabase
20 .from("publications")
21 .select("uri, record")
22 .ilike("record->>name", `%${query}%`)
23 .limit(limit);
24
25 if (error) {
26 throw new Error(`Failed to search publications: ${error.message}`);
27 }
28
29 // Deduplicate records that may exist under both pub.leaflet and site.standard namespaces
30 const publications = deduplicateByUri(rawPublications || []);
31
32 const result = publications.map((p) => {
33 const record = p.record as { name?: string };
34 return {
35 uri: p.uri,
36 name: record.name || "Untitled",
37 url: getPublicationURL(p),
38 };
39 });
40
41 return { result: { publications: result } };
42 },
43});